package oop.controller.action.test;

import java.io.File;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;

import org.apache.commons.lang.ObjectUtils;
import org.docx4j.openpackaging.exceptions.Docx4JException;

import oop.conf.Config;
import oop.controller.ControllerServlet;
import oop.controller.action.DefaultAction;
import oop.data.Test;
import oop.data.TestVersion;
import oop.data.User;
import oop.db.dao.TestDAO;
import oop.db.dao.TestVersionDAO;
import oop.wml.hcwg.docx.DocXDocument;

@SuppressWarnings("unused")
public class SaveDocxAction extends DefaultAction {
	public SaveDocxAction() {
		// default constructor
	}

	@Override
	public void performImpl() throws Exception{
		long testId = Long.parseLong(request.getParameter("testid"));
		Test test = TestDAO.fetchById(testId);
		
		String verIdStr = request.getParameter("verid");
		TestVersion version;
		
		if ((verIdStr == null)||(verIdStr.length() == 0)) {
			version = TestVersionDAO.fetchRandomlyByTest(testId);
			if (version == null) {
				version = TestVersionDAO.create(null, test);
			}
		}else{
			long verId = Long.parseLong(verIdStr);	
			version = TestVersionDAO.fetchById(verId);
		}
		
		String savePath = getController().getServletContext().getRealPath("/");
		DocXDocument newDocX = new DocXDocument(test, version, savePath);
		try {
			newDocX.create();
		} catch (NullPointerException e) {
			throw e;
		} catch (JAXBException e) {
			error("Quá trình tạo gặp sự cố!");
			return;
		} catch (SQLException e) {
			throw e;
		} catch (Docx4JException e) {
			error("Không thể tạo hoặc lưu file này!");
			return;
		}
				
		//need to save docx list?
		response.sendRedirect(Config.get().getHomeDir() + "/" + newDocX.getRelativePath());
		setPreventForward(true);
	}
}
